package ch.fhnw.qualiscan.application.pages;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import ch.fhnw.qualiscan.Config;
import ch.fhnw.qualiscan.application.models.SurveyModel;
import ch.fhnw.qualiscan.core.Page;
import ch.fhnw.qualiscan.core.db.pojos.Survey;
import ch.fhnw.qualiscan.core.db.pojos.SurveyUserRole;
import ch.fhnw.qualiscan.core.helpers.EmailHelper;

public class CronJob extends Page {

	SurveyModel surveyModel;
	EmailHelper emailHelper;
	
	@Override
	public void buildLayout() {
		
		surveyModel = new SurveyModel();
		emailHelper = new EmailHelper();
		
		Date dateNow = new Date();
		List<Survey> sendMailSurveyList = new ArrayList<Survey>();
		List<Survey> surveyList = surveyModel.getAllSurveys();
		
		/*
		 * Select Surveys, where the coordinator needs to be informed about the deadline.
		 */
		for (int i = 0; i < surveyList.size(); i++) {
			if (surveyList.get(i).getStage().getId() == Config.STAGE_SURVEY) {
				if (dateNow.compareTo(surveyList.get(i).getCompletiondate()) < 0) {
					long diff = surveyList.get(i).getCompletiondate().getTime() - dateNow.getTime();
					long diffDay = diff /(1000 * 60 * 60 * 24);
					if (diffDay <= 1) {
						sendMailSurveyList.add(surveyList.get(i));
					}
				}
			}
		}
		
		/*
		 * Get the coordinators email address and send emails
		 */
		for(int a = 0; a < sendMailSurveyList.size(); a++) {
			List<SurveyUserRole> coordinatorList = surveyModel.getCoordinatorsOfSurvey(sendMailSurveyList.get(a));
			for(int j = 0; j < coordinatorList.size(); j++) {
				emailHelper.sendCoordinatorReminderEmail(coordinatorList.get(j).getUser(), sendMailSurveyList.get(a));
			}
		}
	}
	
	@Override
	public void setNeededPermissions() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void initModelsAndHelpers() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void initComponents() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void thirdParameterChanged(String currentUrl) {
		// TODO Auto-generated method stub
		
	}

}
